package com.hisan.freeride.home.activity;

import android.os.Bundle;

import com.blankj.utilcode.util.LogUtils;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.databinding.InsuranceDetailsBinding;
import com.hisan.freeride.home.model.IDetails;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tsy.sdk.pay.model.WXBean;
import com.tsy.sdk.pay.weixin.WXPay;

import org.json.JSONObject;

/**
 * 创建时间 : 2017/12/2
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：保险详情
 */
public class InsuranceDetails extends BaseActivity<InsuranceDetailsBinding>{
    private int id;

    @Override
    protected int getLayoutId() {
        return R.layout.insurance_details;
    }

    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        Bundle bundle=getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            id=bundle.getInt("id");
        }
    }

    @Override
    protected void initEvent() {
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.status.setOnClickListener(v -> {
            String status=mBinding.status.getText().toString();
            if (status.equals("去支付")){
                WxPayopen(id+"");
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<IDetails>get(AppConfig.sdetail)
                .tag(this)
                .params("id",id)
                .execute(new DialogCallback<IDetails>(this){
                    @Override
                    public void onSuccess(Response<IDetails> response) {
                        super.onSuccess(response);
                        LogUtils.v("xxx",response.body());
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            showData();
                            if (isOk(response)){
                                mBinding.title.setText(response.body().getSafety().getTitle());
                                mBinding.content.setText(response.body().getSafety().getContent());
                                mBinding.name.setText(response.body().getName());
                                mBinding.orderNo.setText(response.body().getOrder_no());
                                switch (response.body().getOrder_status()){
                                    case 0:
                                        mBinding.orderStatus.setText("去支付");
                                        mBinding.status.setText("去支付");
                                        break;
                                    case 1:
                                        mBinding.orderStatus.setText("已支付");
                                        mBinding.status.setText("已支付");
                                        break;
                                    case 2:
                                        mBinding.orderStatus.setText("已生效");
                                        mBinding.status.setText("已生效");
                                        break;
                                    case -1:
                                        mBinding.orderStatus.setText("已取消");
                                        mBinding.status.setText("已取消");
                                        break;
                                }
                                mBinding.policyholder.setText(response.body().getPolicyholder());
                                mBinding.phone.setText(response.body().getMobile());
                                mBinding.cardType.setText(response.body().getCard_type());
                                mBinding.cardNumber.setText(response.body().getCard_number());
                                mBinding.time.setText(response.body().getCreate_time());
                            }else {
                                showErrorView(response.code());
                            }
                        }else {
                            noData();
                        }
                    }

                    @Override
                    public void onError(Response<IDetails> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }



    //付款
    private void WxPayopen(String  ids) {
        OkGo.post(AppConfig.unifiedorder)
                .tag(this)
                .params("ids",ids)
                .params("module",1)
                .params("mode",1)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(Response<Object> response) {
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                try {
                                    String data= GsonUtils.GsonString(response.body());
                                    JSONObject json=new JSONObject(data);

                                    JSONObject mjson=json.getJSONObject("pay_data");
                                    if (!CollectionUtils.isNullOrEmpty(mjson)){
                                        WXBean wxBean=new WXBean();
                                        String appid=mjson.getString("appid");
                                        wxBean.setAppid(appid);
                                        int partnerid=mjson.getInt("partnerid");
                                        wxBean.setPartnerid(partnerid);
                                        String prepayid=mjson.getString("prepayid");
                                        wxBean.setPrepayid(prepayid);
                                        String pack=mjson.getString("package");
                                        wxBean.setPackageX(pack);
                                        String Sign=mjson.getString("sign");
                                        wxBean.setSign(Sign);
                                        String noncestr=mjson.getString("noncestr");
                                        wxBean.setNoncestr(noncestr);
                                        int timestamp=mjson.getInt("timestamp");
                                        wxBean.setTimestamp(timestamp);
                                        if (!CollectionUtils.isNullOrEmpty(wxBean))
                                            doWXPay(wxBean);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else {
                                showError(response);
                            }
                        }
                    }
                    @Override
                    public void onError(Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }


    /**
     * 微信支付
     * @param pay_param 支付服务生成的支付参数
     */
    private void doWXPay(WXBean pay_param) {

        String wx_appid = AppConfig.APP_ID;     //替换为自己的appid
        WXPay.init(this, wx_appid);      //要在支付前调用
        WXPay.getInstance().doPay(pay_param, new WXPay.WXPayResultCallBack() {
            //支付成功
            @Override
            public void onSuccess() {
                showSuccessToast("付款成功，如果您的行程被系统或车主取消，我们将通过微信红包的方式，给您返还保险费用。");
                loadData(true);
            }
            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:{
                        showSuccessToast("未安装微信或微信版本过低");
                        break;
                    }
                    case WXPay.ERROR_PAY_PARAM:{
                        showSuccessToast("参数错误");
                        break;
                    }
                    //支付失败
                    case WXPay.ERROR_PAY:{
                        showSuccessToast("支付失败");
                        break;
                    }
                }
            }
            @Override
            public void onCancel() {
                showSuccessToast("用户取消");
            }
        });

    }
}
